import React, { useEffect, useState } from "react";
import { Breadcrumb } from "antd";
import { useMatches, useNavigate } from "react-router-dom";

const CustomBreadcrumb = () => {
  const [breadcrumbItems, setBreadcrumbItems] = useState([]);
  const matches = useMatches();
  const navigate = useNavigate(); // 用于编程式导航

  useEffect(() => {
    // 1. 过滤掉无效路由（无 handle 或无标题的路由，如根路径默认匹配项）
    const validMatches = matches.filter(
      (match) => match.handle?.title && match.handle.title !== "Unknown"
    );

    // 2. 生成面包屑项（支持点击跳转）
    const items = validMatches.map((match, index) => {
      const isLastItem = index === validMatches.length - 1; // 是否为当前页

      return {
        title: match.handle?.title || "未知页面",
        // 3. 非当前页添加点击事件，实现跳转
        onClick: isLastItem
          ? undefined // 当前页禁用点击
          : () => {
              // 优先使用 handle 中拼接好的完整路径，确保跳转正确
              navigate(match.handle?.path || match.pathname, { replace: true });
            },
      };
    });

    setBreadcrumbItems(items);
  }, [matches, navigate]);

  //   return <Breadcrumb items={breadcrumbItems} style={{color:'#fff'}}  className="custom-breadcrumb" />;
  return (
    <Breadcrumb
      items={breadcrumbItems}
    />
  );
};

export default CustomBreadcrumb;
